package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pdd.mall.dto.MerchantLoginParam;
import com.pdd.mall.dto.UpdatePasswordParam;
import com.pdd.mall.entity.Merchant;
import com.pdd.mall.mapper.MerchantMapper;
import com.pdd.mall.service.MerchantService;
import com.pdd.mall.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 商家服务实现类
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(MerchantLoginParam param) {
        try {
            // 直接查询商家并验证密码，避免使用AuthenticationManager导致的循环依赖
            Merchant merchant = getMerchantByUsername(param.getUsername());
            if (merchant == null) {
                return null;
            }

            // 验证密码
            if (!param.getPassword().equals(merchant.getPassword())) {
                return null;
            }

            // 创建UserDetails对象
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_MERCHANT"));
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                merchant.getUsername(),
                merchant.getPassword(),
                merchant.getStatus() == 1,
                true,
                true,
                true,
                authorities
            );

            // 生成JWT令牌
            return jwtTokenUtil.generateToken(userDetails);
        } catch (Exception e) {
            // 打印详细错误信息
            System.err.println("商家登录失败，详细错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Merchant getMerchantInfo(String username) {
        return getMerchantByUsername(username);
    }

    @Override
    public Merchant getMerchantByUsername(String username) {
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return merchantMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean updatePassword(String username, UpdatePasswordParam param) {
        // 获取商家信息
        Merchant merchant = getMerchantByUsername(username);
        if (merchant == null) {
            return false;
        }

        // 验证旧密码
        if (!param.getOldPassword().equals(merchant.getPassword())) {
            return false;
        }

        // 更新密码
        UpdateWrapper<Merchant> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username", username);
        updateWrapper.set("password", passwordEncoder.encode(param.getNewPassword()));

        return merchantMapper.update(null, updateWrapper) > 0;
    }
}
